package first.group.ssh.packet;

import first.group.ssh.SSHConsts;
import first.group.ssh.packet.reader.IntegerReader;
import first.group.ssh.packet.reader.StringReader;
import first.group.ssh.packet.writer.StringWriter;
import java.nio.ByteBuffer;

public class ChannelOpenPacket extends Packet {

    public final String channelType;
    public final int senderChannel;
    public final int initialWindowSize;
    public final int maximumPacketSize;
    public final byte[] payload;

    public ChannelOpenPacket(
            String channelType,
            int senderChannel,
            int initialWindowSize,
            int maximumPacketSize,
            byte[] payload
    ) {
        super(SSHConsts.SSH_MSG_CHANNEL_OPEN);
        this.channelType = channelType;
        this.senderChannel = senderChannel;
        this.initialWindowSize = initialWindowSize;
        this.maximumPacketSize = maximumPacketSize;
        this.payload = payload;
    }

    public static PacketParser<ChannelOpenPacket> PARSER = new ChannelOpenPacket.Parser();

    private static class Parser extends PacketParser<ChannelOpenPacket> {

        @Override
        public ChannelOpenPacket parse(ByteBuffer buffer) {
            var channelType = StringReader.readString(buffer);
            if (channelType == null) {
                return null;
            }
            var senderChannel = IntegerReader.readInteger(buffer);
            if (senderChannel == null) {
                return null;
            }
            var initialWindowSize = IntegerReader.readInteger(buffer);
            if (initialWindowSize == null) {
                return null;
            }
            var maximumPacketSize = IntegerReader.readInteger(buffer);
            if (maximumPacketSize == null) {
                return null;
            }
            var payload = new byte[buffer.remaining()];
            buffer.get(payload);
            return new ChannelOpenPacket(channelType, senderChannel, initialWindowSize, maximumPacketSize, payload);
        }
    }

    @Override
    public void write(ByteBuffer buffer) {
        StringWriter.writeString(buffer, channelType);
        buffer.putInt(senderChannel);
        buffer.putInt(initialWindowSize);
        buffer.putInt(maximumPacketSize);
        buffer.put(payload);
    }
}
